package org.net5ijy.cloud.plugin.feign.core;

import org.net5ijy.cloud.plugin.feign.core.model.FeignClassAndModel;
import org.net5ijy.cloud.plugin.feign.core.model.FeignClientClass;
import org.net5ijy.cloud.plugin.feign.core.model.FeignModel;
import org.net5ijy.cloud.plugin.feign.core.util.ZipUtil.Text;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * FeignClassAndModelResolver
 *
 * @author XGF
 * @date 2020/11/20 14:06
 */
public class FeignClassAndModelResolver {

  public static List<Text> resolveFeignClientClassList(
      List<FeignClientClass> feignClientClasses) throws IOException, TemplateException {

    List<Text> pathAndFileContents = new ArrayList<>();

    for (FeignClientClass feignClientClass : feignClientClasses) {

      // 生成feign接口
      String feignClient = TemplateProcessor.parseFeignClient(feignClientClass);

      Text pathAndFileContent = new Text();

      pathAndFileContent.setText(feignClient);
      pathAndFileContent.setFileName(feignClientClass.getPackageName().replace('.', '/') + "/" + feignClientClass.getFeignClassName() + ".java");

      pathAndFileContents.add(pathAndFileContent);

      if (feignClientClass.isFeignFallback()) {
        // 生成fallback
        String feignClientFallBack = TemplateProcessor.parseFeignClientFallBack(feignClientClass);
        
        Text pathAndFileContent2 = new Text();
        
        pathAndFileContent2.setText(feignClientFallBack);
        pathAndFileContent2
        .setFileName(
            "fallback/" + feignClientClass.getFeignClassName() + "FallBackFactory.java");
        
        pathAndFileContents.add(pathAndFileContent2);
      }
    }

    return pathAndFileContents;
  }

  public static List<Text> resolveFeignModelList(List<FeignModel> feignModels)
      throws IOException, TemplateException {

    List<Text> pathAndFileContents = new ArrayList<>();

    for (FeignModel feignModel : feignModels) {

      String model = TemplateProcessor.parseFeignModel(feignModel);

      Text pathAndFileContent = new Text();

      pathAndFileContent.setText(model);

      pathAndFileContent.setFileName(
          feignModel.getPackageName().replace('.', '/') + "/" + feignModel.getModelName()
              + ".java");

      pathAndFileContents.add(pathAndFileContent);
    }

    return pathAndFileContents;
  }
  
  public static List<Text> resolvePom(FeignClassAndModel feignClassAndModel)
      throws IOException, TemplateException {

    List<Text> pathAndFileContents = new ArrayList<>();

    String model = TemplateProcessor.parsePomFile(feignClassAndModel);
    
    Text pathAndFileContent = new Text();
    
    pathAndFileContent.setText(model);
    
    pathAndFileContent.setFileName("pom.xml");
    
    pathAndFileContents.add(pathAndFileContent);

    return pathAndFileContents;
  }
}
